/*
XCommander Extension
http://www.xcommander.ch/
*/

function XCommanderUIInfobar() {
	this.init(this.confirm);
}

XCommanderUIInfobar.prototype = {
	init : function(callback) {
		var hasXcommand = $("head").find("link[rel^='xcommand'][href$='.xcmd']");
		if(hasXcommand.length > 0) {
			xcommander.lib.xhr.send({
				url : 'xcommander://templates/infobar.html',
				type : 'text'
			}, function(data) {
				var infobar = data.response.toString();
				$(infobar).appendTo(document.body);
				$("#xcommander_infobar_message .close").click(function() {
					$("#xcommander_infobar").slideUp("fast");
				});
				$("#xcommander_infobar_subscribe").click(function() {
					$("#xcommander_infobar").slideUp("fast", callback);
				});
				$("#xcommander_infobar").slideToggle("fast", "linear");
			});
		}
	},
	confirm : function() {
		xcommander.lib.xhr.send({
			url : 'xcommander://templates/confirm.html',
			type : 'text'
		}, function(data) {
			var confirm = data.response.toString().replace("{$source}", "<b><a href='" + document.URL + "' target='_blank'>" + document.domain + "</a></b>");
			$(confirm).appendTo(document.body)

			var xcommand = "http://" + document.domain + "/" + $("head > link[rel^='xcommand']").attr("href");

			xcommander.lib.xhr.send({
				'url' : xcommand,
				'type' : 'text',
				'headers' : {
					'Cache-Control' : 'no-cache'
				}
			}, function(data) {
				if($.isEmptyObject(data.response)) {
					$("#xcommander_confirm_confirm").attr({
						disabled : 'disabled'
					})
				}
				$("#xcommander_confirm_command").text(data.response.toString());
				$("#xcommander_confirm_cancel").click(function() {
					$("#xcommander_confirm_panel").fadeOut("fast", function() {
						$("#xcommander_confirm_overlay").fadeOut("fast");
					})
				});
				$("#xcommander_confirm_confirm").click(function() {
					$("#xcommander_confirm_panel").fadeOut("fast", function() {
						$("#xcommander_confirm_overlay").fadeOut("fast");
						xcommander.xcommand.validate(data.response.toString(), function(data) {
							if(data.type == "valid") {
								xcommander.lib.browser.navigateTo('xcommander://options.html', true);
							} else {
								alert("Ungültiges XCommand! { Error: " + data.error + " }");
							}
						})
					})
				});

				$("#xcommander_confirm_overlay").fadeIn("fast", function() {
					$("#xcommander_confirm_panel").fadeIn("slow");
				});
			});
		});
	}
}